package wonders.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import wonders.mapper.UserMapper;

import javax.sql.DataSource;

@Configuration
public class SpringMybatisConfig {

    /**
     * 数据源
     *
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://10.1.192.113:3306/liu_test");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
        sqlSessionTemplate.getConfiguration().setMapUnderscoreToCamelCase(true); // 设置驼峰映射
        sqlSessionTemplate.getConfiguration().addMapper(UserMapper.class); // 配置mapper位置
        return sqlSessionTemplate;
    }

    @Bean
    public UserMapper userMapper() throws Exception {
        return sqlSessionTemplate().getMapper(UserMapper.class);
    }
}
